package com.gmcloud.common.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gmcloud.common.utils.constant.CommonConstants;
import com.gmcloud.common.utils.R;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zl.sir
 * @version 1.0
 * @since 2022/8/17 12:12
 * 用于从客户端请求凭据。例如，它可能会重定向到登录页面或发送WWW-Authenticate标头
 * 客户端异常处理 AuthenticationException 不同细化异常处理
 */
public class ResourceAuthExceptionEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper;

    public ResourceAuthExceptionEntryPoint(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        response.setCharacterEncoding(CommonConstants.UTF8);
        response.setContentType(CommonConstants.CONTENT_TYPE);
        R<String> r = new R<>();
        r.setCode(CommonConstants.FAIL);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        if (authException != null) {
            r.setMessage("error");
            r.setResult(authException.getMessage());
        }

        // 针对令牌过期返回特殊的 424
        if (authException instanceof InvalidBearerTokenException) {
            response.setStatus(HttpStatus.FAILED_DEPENDENCY.value());
            r.setMessage("token expire");
        }

        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(r));
    }
}
